package com.edu.buaa;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "ZiweiApp.db";
    private static final int DATABASE_VERSION = 1;

    // 用户表
    private static final String TABLE_USERS = "users";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_USERNAME = "username";
    private static final String COLUMN_PASSWORD = "password";
    private static final String COLUMN_EMAIL = "email";

    // 生辰八字表
    private static final String TABLE_BIRTH_DATA = "birth_data";
    private static final String COLUMN_USER_ID = "user_id";
    private static final String COLUMN_GENDER = "gender";
    private static final String COLUMN_BIRTH_YEAR = "birth_year";
    private static final String COLUMN_BIRTH_MONTH = "birth_month";
    private static final String COLUMN_BIRTH_DAY = "birth_day";
    private static final String COLUMN_BIRTH_HOUR = "birth_hour";
    private static final String COLUMN_SOLAR_DATE = "solar_date";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建用户表
        String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_USERS + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COLUMN_USERNAME + " TEXT UNIQUE,"
                + COLUMN_PASSWORD + " TEXT,"
                + COLUMN_EMAIL + " TEXT"
                + ")";
        db.execSQL(CREATE_USERS_TABLE);

        // 创建生辰八字表
        String CREATE_BIRTH_DATA_TABLE = "CREATE TABLE " + TABLE_BIRTH_DATA + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COLUMN_USER_ID + " INTEGER,"
                + COLUMN_GENDER + " TEXT,"
                + COLUMN_BIRTH_YEAR + " INTEGER,"
                + COLUMN_BIRTH_MONTH + " INTEGER,"
                + COLUMN_BIRTH_DAY + " INTEGER,"
                + COLUMN_BIRTH_HOUR + " INTEGER,"
                + COLUMN_SOLAR_DATE + " TEXT,"
                + "FOREIGN KEY(" + COLUMN_USER_ID + ") REFERENCES " + TABLE_USERS + "(" + COLUMN_ID + ")"
                + ")";
        db.execSQL(CREATE_BIRTH_DATA_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_BIRTH_DATA);
        onCreate(db);
    }

    // 添加用户
    public boolean addUser(String username, String password, String email) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_USERNAME, username);
        values.put(COLUMN_PASSWORD, password);
        values.put(COLUMN_EMAIL, email);

        long result = db.insert(TABLE_USERS, null, values);
        return result != -1;
    }

    // 检查用户名是否存在
    public boolean checkUsername(String username) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_USERS,
                new String[]{COLUMN_ID},
                COLUMN_USERNAME + " = ?",
                new String[]{username},
                null, null, null);

        boolean exists = cursor.getCount() > 0;
        cursor.close();
        return exists;
    }

    // 验证登录
    public boolean checkLogin(String username, String password) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_USERS,
                new String[]{COLUMN_ID},
                COLUMN_USERNAME + " = ? AND " + COLUMN_PASSWORD + " = ?",
                new String[]{username, password},
                null, null, null);

        boolean valid = cursor.getCount() > 0;
        cursor.close();
        return valid;
    }

    // 获取用户ID
    public int getUserId(String username) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_USERS,
                new String[]{COLUMN_ID},
                COLUMN_USERNAME + " = ?",
                new String[]{username},
                null, null, null);

        if (cursor.moveToFirst()) {
            @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex(COLUMN_ID));
            cursor.close();
            return id;
        }
        cursor.close();
        return -1;
    }

    // 保存生辰八字数据
    public boolean saveBirthData(int userId, String gender, int year, int month, int day, int hour, String solarDate) {
        SQLiteDatabase db = this.getWritableDatabase();
        
        // 先检查是否已存在数据
        Cursor cursor = db.query(TABLE_BIRTH_DATA,
                new String[]{COLUMN_ID},
                COLUMN_USER_ID + " = ?",
                new String[]{String.valueOf(userId)},
                null, null, null);

        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_ID, userId);
        values.put(COLUMN_GENDER, gender);
        values.put(COLUMN_BIRTH_YEAR, year);
        values.put(COLUMN_BIRTH_MONTH, month);
        values.put(COLUMN_BIRTH_DAY, day);
        values.put(COLUMN_BIRTH_HOUR, hour);
        values.put(COLUMN_SOLAR_DATE, solarDate);

        long result;
        if (cursor.getCount() > 0) {
            // 更新现有数据
            result = db.update(TABLE_BIRTH_DATA, values, COLUMN_USER_ID + " = ?", new String[]{String.valueOf(userId)});
        } else {
            // 插入新数据
            result = db.insert(TABLE_BIRTH_DATA, null, values);
        }
        
        cursor.close();
        return result != -1;
    }

    // 获取用户的生辰八字数据
    public Cursor getBirthData(int userId) {
        SQLiteDatabase db = this.getReadableDatabase();
        return db.query(TABLE_BIRTH_DATA,
                new String[]{COLUMN_GENDER, COLUMN_BIRTH_YEAR, COLUMN_BIRTH_MONTH, COLUMN_BIRTH_DAY, COLUMN_BIRTH_HOUR, COLUMN_SOLAR_DATE},
                COLUMN_USER_ID + " = ?",
                new String[]{String.valueOf(userId)},
                null, null, null);
    }
}